# coding: utf-8

from celery import shared_task
from services.datamodel.share import stats_logger
import json
from django.http import HttpResponse, JsonResponse
import xlwt
from io import BytesIO
from services.datamodel.student.models import mm_Student, mm_StudentTeam
import logging
app_logger = logging.getLogger("student")
import traceback
from django.db.models import F, Sum
from django.db import transaction
import collections


# @shared_task(ignore_result=True)
# def export_users(start_date, end_date):
#     try:
#         app_logger.error("用户加入")
#         users = mm_Student.filter(created_at__range=[start_date, end_date], level=0).values('created_at', 'avatar',
#                                                                                             'nick_name', 'mobile', 'id')
#         ws = xlwt.Workbook(encoding="UTF-8")
#         w = ws.add_sheet(u'数据')
#         w.write(0, 0, u'注册时间')
#         w.write(0, 1, u'用户昵称')
#         w.write(0, 2, u'用户手机')
#         w.write(0, 3, u'上级代言人昵称')
#         w.write(0, 4, u'上级代言人手机号')
#         w.write(0, 5, u'代言人上级区代')
#         w.write(0, 6, u'区代手机号')
#         w.write(0, 7, u'市代昵称')
#         w.write(0, 8, u'市代手机号')
#         w.write(0, 9, u'省代昵称')
#         w.write(0, 10, u'省代手机号')
#         excel_row = 1
#         datas = collections.defaultdict(list)
#         for v in users:
#             parent_arr = {}
#             parent = mm_StudentTeam.filter(student_id=v['id'], parent__level__in=[1, 2, 3, 4, 5, 6]).\
#                 values('level', 'parent__nick_name', 'parent__mobile', 'parent__level', 'parent_id')
#             for vs in parent:
#                 parent_arr[vs['parent_id']] = {'name': vs['parent__nick_name'], 'mobile': vs['parent__mobile'],
#                                                'level': vs['parent__level']}
#             datas[v['id']].append(parent_arr)
#         for k, v in datas.items():
#             sheng_name = ''
#             sheng_mobile = ''
#             shi_name = ''
#             shi_mobile = ''
#             qu_name = ''
#             qu_mobile = ''
#             dai_name = ''
#             dai_mobile = ''
#             for vs in v[0]:
#                 if v[0][vs]['level'] in [4, 5, 6]:
#                     dai_name = v[0][vs]['name']
#                     dai_mobile = v[0][vs]['mobile']
#                 if v[0][vs]['level'] == 3:
#                     qu_name = v[0][vs]['name']
#                     qu_mobile = v[0][vs]['mobile']
#                 if v[0][vs]['level'] == 2:
#                     shi_name = v[0][vs]['name']
#                     shi_mobile = v[0][vs]['mobile']
#                 if v[0][vs]['level'] == 1:
#                     sheng_name = v[0][vs]['name']
#                     sheng_mobile = v[0][vs]['mobile']
#             user = mm_Student.filter(pk=k).values('created_at', 'nick_name', 'mobile').first()
#             w.write(excel_row, 0, user['created_at'].strftime('%Y-%m-%d %H:%M:%S'))
#             w.write(excel_row, 1, user['nick_name'])
#             w.write(excel_row, 2, user['mobile'])
#             w.write(excel_row, 3, dai_name)
#             w.write(excel_row, 4, dai_mobile)
#             w.write(excel_row, 5, qu_name)
#             w.write(excel_row, 6, qu_mobile)
#             w.write(excel_row, 7, shi_name)
#             w.write(excel_row, 8, shi_mobile)
#             w.write(excel_row, 9, sheng_name)
#             w.write(excel_row, 10, sheng_mobile)
#             excel_row += 1
#         sio = BytesIO()
#         ws.save(sio)
#         sio.seek(0)
#         response = HttpResponse(sio.getvalue(), content_type='application/vnd.ms-excel')
#         response['Content-Disposition'] = 'attachment; filename=stu_info.xls'
#         response.write(sio.getvalue())
#         return response
#     except:
#         err = traceback.format_exc()
#         app_logger.error(err)
#         return False

def export_users(start_date, end_date, channel=None):
    """

    @param start_date:
    @param end_date:
    @return:
    """
    try:
        app_logger.error("用户加入")
        users = mm_Student.filter(created_at__range=[start_date, end_date], level=0).values('created_at', 'avatar',
                                                                                            'nick_name', 'mobile', 'id')
        if channel:
            users = users.filter(channel=channel)
        ws = xlwt.Workbook(encoding="UTF-8")
        w = ws.add_sheet(u'数据')
        w.write(0, 0, u'注册时间')
        w.write(0, 1, u'用户昵称')
        w.write(0, 2, u'用户手机')
        w.write(0, 3, u'上级代言人昵称')
        w.write(0, 4, u'上级代言人手机号')
        w.write(0, 5, u'代言人上级区代')
        w.write(0, 6, u'区代手机号')
        w.write(0, 7, u'市代昵称')
        w.write(0, 8, u'市代手机号')
        w.write(0, 9, u'省代昵称')
        w.write(0, 10, u'省代手机号')
        excel_row = 1
        for v in users:
            sheng_name = ''
            sheng_mobile = ''
            shi_name = ''
            shi_mobile = ''
            qu_name = ''
            qu_mobile = ''
            dai_name = ''
            dai_mobile = ''
            parent = mm_StudentTeam.filter(student_id=v['id'], level=1, status__in=[0, 1, 2]).values(
                'parent__nick_name', 'parent__mobile', 'parent__level', 'parent_id').first()
            while parent:
                if parent['parent__level'] == 1:
                    sheng_name = parent['parent__nick_name']
                    sheng_mobile = parent['parent__mobile']
                elif parent['parent__level'] == 2:
                    shi_name = parent['parent__nick_name']
                    shi_mobile = parent['parent__mobile']
                elif parent['parent__level'] == 3:
                    qu_name = parent['parent__nick_name']
                    qu_mobile = parent['parent__mobile']
                elif parent['parent__level'] in [4, 5, 6]:
                    dai_name = parent['parent__nick_name']
                    dai_mobile = parent['parent__mobile']
                parent = mm_StudentTeam.filter(student_id=parent['parent_id'], level=1, status__in=[0, 1, 2]).values(
                    'parent__nick_name', 'parent__mobile', 'parent__level', 'parent_id').first()
            w.write(excel_row, 0, v['created_at'].strftime('%Y-%m-%d %H:%M:%S'))
            w.write(excel_row, 1, v['nick_name'])
            w.write(excel_row, 2, v['mobile'])
            w.write(excel_row, 3, dai_name)
            w.write(excel_row, 4, dai_mobile)
            w.write(excel_row, 5, qu_name)
            w.write(excel_row, 6, qu_mobile)
            w.write(excel_row, 7, shi_name)
            w.write(excel_row, 8, shi_mobile)
            w.write(excel_row, 9, sheng_name)
            w.write(excel_row, 10, sheng_mobile)
            excel_row += 1
        sio = BytesIO()
        ws.save(sio)
        sio.seek(0)
        response = HttpResponse(sio.getvalue(), content_type='application/vnd.ms-excel')
        response['Content-Disposition'] = 'attachment; filename=stu_info.xls'
        response.write(sio.getvalue())
        return response
    except:
        err = traceback.format_exc()
        app_logger.error(err)
        return JsonResponse({"retcode": 1, "message": "导出失败", "error": err})